package cn.fl.ass.service.impl;

import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.Pager;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.constant.BaseExceptionConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.logger.eum.LogExceptionEnum;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.ass.service.IAssVfInfoService;
import cn.fl.ass.transform.AssVfInfoVOTransform;
import cn.fl.ass.vo.AssVfInfoVO;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.framework.constant.DictionaryConstant;
import cn.fl.project.condition.PrjBscInfoQueryCondition;
import cn.fl.project.condition.PrjCstBscInfoQueryCondition;
import cn.fl.project.condition.PrjLinkManQueryCondition;
import cn.fl.project.condition.PrjPrdDtlQueryCondition;
import cn.fl.project.constant.PrjBscInfoConstant;
import cn.fl.project.constant.PrjPrdPaySchMConstant;
import cn.fl.project.dto.PrjLinkManDTO;
import cn.fl.project.dto.PrjPrdDtlDTO;
import cn.fl.project.dto.PrjPrdPaySchMDTO;
import cn.fl.project.service.*;
import cn.fl.project.vo.PrjBscInfoVO;
import cn.fl.project.vo.PrjCstBscInfoVO;
import cn.fl.project.vo.PrjPrdBscInfoVO;
import cn.fl.risk.api.IRskCstSignLogApiService;
import cn.fl.risk.condition.RskCstSignLogQueryCondition;
import cn.fl.risk.dto.RskCstSignLogDTO;
import cn.fl.sue.api.ISueApplyViewApiService;
import cn.fl.sue.condition.SueApplyViewQC;
import cn.fl.sue.constant.SueDicCode;
import cn.fl.sue.dto.SueApplyViewDTO;
import com.alibaba.fastjson.JSONObject;
import fl.ass.facade.api.IAssVfInfoApi;
import fl.ass.facade.constant.AssVfInfoConstant;
import fl.ass.facade.dto.AssVfInfoDTO;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**
 * @Description: 资产核销信息表 客户端服务层接口实现
 * @Description: 业务层方法名称前缀：新增：add* 删除：remove* 修改：modify* 查询对象：select* get* 批量：batch* 查询集合：search*
 */
@Service
public class AssVfInfoServiceImpl implements IAssVfInfoService {

    /**
     * 日志
     */
    private static final Logger logger = LoggerFactory.getLogger(AssVfInfoServiceImpl.class);

    @Autowired
    private IAssVfInfoApi assVfInfoApi;

    @Autowired
    private IPrjBscInfoService prjBscInfoService;

    @Autowired
    private IPrjPrdBscInfoService prjPrdBscInfoService;

    @Autowired
    private IPrjCstBscInfoService prjCstBscInfoService;

    @Autowired
    private IRskCstSignLogApiService rskCstSignLogApiService;

    @Autowired
    private IPrjPrdPaySchMApiService prjPrdPaySchMApiService;

    @Autowired
    private IProjectApiService projectApiService;

    @Autowired
    private ISueApplyViewApiService sueApplyViewApiService;

    @Autowired
    private ISysDictionaryApiService sysDictionaryApiService;

    @Override
    public AssVfInfoVO selectById(Long id) throws BaseException {
        if (StringUtils.isEmpty(id)) {
            BaseLogUtils.info(logger, "selectById", "主键参数不能为空!", CurrentThreadContext.getCurrentUserName());
            throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, "获取对象主键不能为空!");
        }
        //TODO 业务逻辑
        AssVfInfoDTO dto = null;//this.自定义ApiService.selectAssVfInfoDTOById(id);
        return AssVfInfoVOTransform.toVO(dto);
    }

    @Override
    public Long add(AssVfInfoVO entity) throws BaseException {
        if (null == entity) {
            BaseLogUtils.info(logger, "add", "新增对象不存在!");
            throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, "新增对象不存在!");
        }
        ;
        //return this.assVfInfoApiService.add(AssVfInfoVOTransform.toDTO(entity));
        //TODO 业务逻辑
        return null;
    }

    @Override
    public boolean removeById(Long id) throws BaseException {
        if (StringUtils.isEmpty(id)) {
            BaseLogUtils.info(logger, "removeById", "删除对象主键不能为空!");
            throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, "删除对象主键不能为空!");
        }
        ;
        //return this.assVfInfoApiService.removeAssVfInfoDTOById(id);
        //TODO 业务逻辑
        return false;
    }

    /**
     * 删除
     *
     * @param ids
     * @return
     */
    public boolean removeByIds(List<Long> ids) throws BaseException {
        if (CollectionUtils.isEmpty(ids)) {
            BaseLogUtils.info(logger, "removeByIds", "删除主键参数集合不能为空!", CurrentThreadContext.getCurrentUserName());
            throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, "删除对象主键不能为空!");
        }
        ;
        return false;
    }

    @Override
    public boolean modify(AssVfInfoVO entity) throws BaseException {
        if (null == entity) {
            BaseLogUtils.info(logger, "modify", "修改对象不能为空!");
            throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, "修改对象不能为空!");
        }
        ;
        //return this.assVfInfoApiService.modifyAssVfInfoDTO(AssVfInfoVOTransform.toDTO(entity));
        //TODO 业务逻辑
        return false;
    }

    @Override
    public Pager searchListPage(Pager page) throws BaseException {
        if (null == page) {
            page = new Pager();
        }
        return this.assVfInfoApi.searchAssVfInfoListPage(page);
    }

    /**
     * 解析读取excel里的内容
     *
     * @param fis
     * @param result
     * @return
     */
    @Override
    public DataResultVO parseExcel(InputStream fis, DataResultVO result) throws Exception {
        List<String> paySchNos = new ArrayList<>();
        try {
            HSSFWorkbook book = new HSSFWorkbook(fis);
            HSSFSheet sheet = book.getSheetAt(0);
            int rowCount = sheet.getPhysicalNumberOfRows(); //获取总行数
            //判断一下，是否下载了模板
            HSSFCell cellT = sheet.getRow(0).getCell(0);
            String cellTValue = cellT.getStringCellValue().trim();
            if (StringUtils.isEmpty(cellTValue)) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo("请下载模板，然后填写数据!");
                return result;
            }
            if (!"*支付表号".equals(cellTValue)) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo("请下载模板，然后填写数据!!!");
                return result;
            }

            for (int i = 1; i < rowCount; i++) {//从第2行开始
                HSSFCell cell = sheet.getRow(i).getCell(0);
                cell.setCellType(1);
                String cellValue = cell.getStringCellValue().trim();
                cellValue.replace("\\s", "");
                cellValue.replace("\\n", "");//回车符号
                cellValue.replace("\\t", "");//水平制表符
                cellValue.replace("\\r", "");//换行符
                if (StringUtils.isNotBlank(cellValue)) {
                    paySchNos.add(cellValue);
                }
            }
        } catch (IOException e) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo("请下载模板");
            BaseLogUtils.error(logger, "parseExcel", "错误[Exception] -ERROR:" + e.getMessage(), CurrentThreadContext.getCurrentUserName());
            e.getStackTrace();
            return result;
        } catch (NullPointerException e) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo("解析Excel出错，请删掉Excel中支付表号为空的数据行!");
            BaseLogUtils.error(logger, "parseExcel", "错误[Exception] -ERROR:" + e.getMessage(), CurrentThreadContext.getCurrentUserName());
            e.getStackTrace();
        }
        if (CollectionUtils.isEmpty(paySchNos)) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo("上传的EXCEL中支付表编号不允许为空，请核查!");
            return result;
        }
        result.setData(paySchNos);
        BaseLogUtils.newLogger("解析支付表号的数据为：").setKeys(JSONObject.toJSONString(paySchNos)).info();
        return result;
    }

    @Override
    public boolean handlePaySchNosAndInsertVfInfo(List<String> paySchNoList, Long crtUsrId) throws BaseException {
        return this.assVfInfoApi.handlePaySchNosAndInsertVfInfo(paySchNoList, crtUsrId);
    }

    @Override
    public DataResultVO getVfDetailViewData(Long infoId) throws BaseException {
        try {
            AssVfInfoVO assVfInfoVO = AssVfInfoVOTransform.toVO(assVfInfoApi.getAssVfInfo(infoId));
            Assert.notNull(assVfInfoVO, "资产核销数据为空");
            DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "");
            PrjBscInfoQueryCondition prjBscInfoQueryCondition = new PrjBscInfoQueryCondition();
            prjBscInfoQueryCondition.setLsCntNo(assVfInfoVO.getCntNo());
            prjBscInfoQueryCondition.setIsDel(BaseConstant.IS_YESNO_NO);
            // 项目基础信息
            List<PrjBscInfoVO> prjBscInfoDTOS = prjBscInfoService.searchList(prjBscInfoQueryCondition);
            if (CollectionUtils.isEmpty(prjBscInfoDTOS)) {
                throw new BaseException("未查到项目基础信息数据");
            }
            PrjBscInfoVO prjBscInfoVO = prjBscInfoDTOS.get(0);
            assVfInfoVO.setPrjTypCdNm(prjBscInfoVO.getPrjTypCdNm());
            assVfInfoVO.setBuOrgNm(prjBscInfoVO.getBuOrgCdNm());
            assVfInfoVO.setCstMgrNm(prjBscInfoVO.getCstMgrNm());
            // 支付表主表信息
            List<PrjPrdPaySchMDTO> prjPrdPaySchMDTOS = prjPrdPaySchMApiService.selectEnabledAndWsList(assVfInfoVO.getPaySchId());
            PrjPrdDtlDTO prjPrdDtlDTO = null;
            if (CollectionUtils.isNotEmpty(prjPrdPaySchMDTOS)) {
                for (PrjPrdPaySchMDTO paySchMDTO : prjPrdPaySchMDTOS) {
                    if (PrjPrdPaySchMConstant.PAY_SCH_TYP_CD_WS.equals(paySchMDTO.getPaySchTypCd())) {
                        PrjPrdDtlQueryCondition prjPrdDtlQueryCondition = new PrjPrdDtlQueryCondition();
                        prjPrdDtlQueryCondition.setPaySchId(paySchMDTO.getId());
                        prjPrdDtlQueryCondition.setIsDel(BaseConstant.IS_YESNO_NO);
                        // 项目产品明细信息
                        List<PrjPrdDtlDTO> prjPrdDtlDTOS = projectApiService.selectPrjPrdDtlList(prjPrdDtlQueryCondition);
                        if (CollectionUtils.isNotEmpty(prjPrdDtlDTOS)) {
                            prjPrdDtlDTO = prjPrdDtlDTOS.get(0);
                            break;
                        }
                    }
                }
            }
            Assert.notNull(prjPrdDtlDTO, "未查到项目产品明细数据");
            assVfInfoVO.setLnkCompNm(prjPrdDtlDTO.getLnkCompNm());
            // 项目产品信息
            PrjPrdBscInfoVO prjPrdBscInfoVO = prjPrdBscInfoService.selectById(prjPrdDtlDTO.getPrjPrdId());
            Assert.notNull(prjPrdBscInfoVO, "未查到项目产品数据");
            assVfInfoVO.setSplNm(prjPrdBscInfoVO.getSplNm());
            assVfInfoVO.setPrdNm(prjPrdBscInfoVO.getPrdNm());
            PrjCstBscInfoQueryCondition prjCstBscInfoQueryCondition = new PrjCstBscInfoQueryCondition();
            prjCstBscInfoQueryCondition.setPrjId(prjBscInfoVO.getId());
            prjCstBscInfoQueryCondition.setCstRlTyp(PrjBscInfoConstant.CODE_CST_RL_SPONSOR);
            List<PrjCstBscInfoVO> prjCstBscInfoVOS = prjCstBscInfoService.searchList(prjCstBscInfoQueryCondition);
            StringBuffer sb = new StringBuffer();
            List<Long> guarIds = new ArrayList<>();
            if (CollectionUtils.isNotEmpty(prjCstBscInfoVOS)) {
                for (PrjCstBscInfoVO prjCstBscInfoVO : prjCstBscInfoVOS) {
                    sb.append(prjCstBscInfoVO.getCstNm() + "、");
                    guarIds.add(prjCstBscInfoVO.getCstId());
                }
            }
            PrjLinkManQueryCondition qc = new PrjLinkManQueryCondition();
            qc.setPrjId(prjBscInfoVO.getId());
            List<PrjLinkManDTO> prjLinkManDTOS = projectApiService.searchPrjLinkManList(qc, CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd());
            if (CollectionUtils.isNotEmpty(prjLinkManDTOS)) {
                for (int i = 0; i < prjLinkManDTOS.size(); i++) {
                    sb.append(prjLinkManDTOS.get(i).getLnkNm());
                    if (i != prjLinkManDTOS.size() - 1) {
                        sb.append("、");
                    }
                }
            }
            assVfInfoVO.setGuarNm(sb.toString());
            prjCstBscInfoQueryCondition.setCstRlTyp(PrjBscInfoConstant.CODE_CST_RL_SPONSOR);
            SueApplyViewQC sueApplyViewQC = new SueApplyViewQC();
            sueApplyViewQC.setDataId(prjBscInfoVO.getId());
            // 最新的诉讼数据
            SueApplyViewDTO sueApplyViewDTO = sueApplyViewApiService.selectLatestSueApplyView(sueApplyViewQC);
            if (null != sueApplyViewDTO) {
                Map<String, String> sueStsCdDic = sysDictionaryApiService.searchGroupToMap(AssVfInfoConstant.SYS_CD, AssVfInfoConstant.ORG_CD, SueDicCode.SUE0007);
                assVfInfoVO.setSueStsCdNm(sueStsCdDic.get(sueApplyViewDTO.getSueStsCd()));
            }
            Map<String, String> signResTypeDic = sysDictionaryApiService.searchGroupToMap(AssVfInfoConstant.SYS_CD, AssVfInfoConstant.ORG_CD, DictionaryConstant.CODE_GRP_NM_SIGN_RES_TYPE);
            RskCstSignLogQueryCondition rskCstSignLogQueryCondition = new RskCstSignLogQueryCondition();
            rskCstSignLogQueryCondition.setCstId(assVfInfoVO.getCstId());
            rskCstSignLogQueryCondition.setCstTypeCd("1");
            // 客户黑名单
            List<RskCstSignLogDTO> rskCstSignLogDTOS = rskCstSignLogApiService.searchRskCstSignLogList(rskCstSignLogQueryCondition);
            if (CollectionUtils.isNotEmpty(rskCstSignLogDTOS)) {
                assVfInfoVO.setCstBlkList(signResTypeDic.get(rskCstSignLogDTOS.get(0).getSignResType()));
            }
            rskCstSignLogQueryCondition.setCstId(prjPrdBscInfoVO.getSplId());
            rskCstSignLogQueryCondition.setCstTypeCd("2");
            // 供应商黑名单
            rskCstSignLogDTOS = rskCstSignLogApiService.searchRskCstSignLogList(rskCstSignLogQueryCondition);
            if (CollectionUtils.isNotEmpty(rskCstSignLogDTOS)) {
                assVfInfoVO.setCstBlkList(signResTypeDic.get(rskCstSignLogDTOS.get(0).getSignResType()));
            }
            rskCstSignLogQueryCondition.setCstId(prjPrdDtlDTO.getLnkCompId());
            rskCstSignLogQueryCondition.setCstTypeCd("3");
            // 挂靠公司黑名单
            rskCstSignLogDTOS = rskCstSignLogApiService.searchRskCstSignLogList(rskCstSignLogQueryCondition);
            if (CollectionUtils.isNotEmpty(rskCstSignLogDTOS)) {
                assVfInfoVO.setCstBlkList(signResTypeDic.get(rskCstSignLogDTOS.get(0).getSignResType()));
            }
            rskCstSignLogQueryCondition.setCstTypeCd("7");
            outer:
            for (Long guarId : guarIds) {
                rskCstSignLogQueryCondition.setCstId(guarId);
                // 担保人黑名单
                rskCstSignLogDTOS = rskCstSignLogApiService.searchRskCstSignLogList(rskCstSignLogQueryCondition);
                if (CollectionUtils.isNotEmpty(rskCstSignLogDTOS)) {
                    for (RskCstSignLogDTO rskCstSignLogDTO : rskCstSignLogDTOS) {
                        if ("3".equals(rskCstSignLogDTO.getSignResType())) {
                            assVfInfoVO.setCstBlkList(signResTypeDic.get(rskCstSignLogDTO.getSignResType()));
                            break outer;
                        } else if ("2".equals(rskCstSignLogDTO.getSignResType())) {
                            assVfInfoVO.setCstBlkList(signResTypeDic.get(rskCstSignLogDTO.getSignResType()));
                            break outer;
                        } else if ("1".equals(rskCstSignLogDTO.getSignResType())) {
                            assVfInfoVO.setCstBlkList(signResTypeDic.get(rskCstSignLogDTO.getSignResType()));
                            break outer;
                        }
                    }
                }
            }
            Map<String, String> vfStsCdMap = sysDictionaryApiService.searchGroupToMap(AssVfInfoConstant.SYS_CD, AssVfInfoConstant.ORG_CD, AssVfInfoConstant.VF_STS_GRP_CD);
            if (vfStsCdMap != null && vfStsCdMap.containsKey(assVfInfoVO.getVfStsCd())) {
                assVfInfoVO.setVfStsCdNm(vfStsCdMap.get(assVfInfoVO.getVfStsCd()));
            }
            result.setData(assVfInfoVO);
            return result;
        } catch (BaseException e) {
            BaseLogUtils.newLogger("查询资产核销明细数据失败").setKeys("infoId:" + infoId).setThrowable(e).error(LogExceptionEnum.COMMON_CODE_0002);
            throw e;
        } catch (Exception e) {
            BaseLogUtils.newLogger("查询资产核销明细数据失败").setKeys("infoId:" + infoId).setThrowable(e).error(LogExceptionEnum.COMMON_CODE_0002);
            throw e;
        }
    }

}
